﻿using System.Threading;
using System.Threading.Tasks;
using System.Web.Mvc;
using System.Linq;
using Api.Web.helper;
using System.Web;
using Api.Common;
using System.Web.Routing;
using System.Web.Mvc.Filters;
using System;

namespace Able.Web.filter
{
    /// <summary>
    /// 必須要傳遞了memberId才能使用的接口上標記，
    /// </summary>
    public class NeedLoginAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (NoNeedLoginAttribute.IsIgnore(filterContext))
            {
                base.OnActionExecuting(filterContext);
                return;
            }

            string controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName.ToLower();
            string actionName = filterContext.ActionDescriptor.ActionName.ToLower();

            var returnUrl = HttpContext.Current.Server.UrlEncode(HttpContext.Current.Request.Url.ToString());
            if (!Th.IsLogin && controllerName != "account" && actionName != "login")
            {
                if (!string.IsNullOrEmpty(HttpContext.Current.Request.QueryString["isajax"])) //表示为ajax请求
                {
                    AjaxMsgHelper.Response(true, "請重新登錄", null, "", false); //请重新登录
                }
                else
                {
                    filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary
                    {
                        {"area", ""},
                        {"controller", "Account"},
                        {"action", "Login"},
                        {"returnUrl", returnUrl}
                    });
                }
            }

            base.OnActionExecuting(filterContext);
        }
    }

    public class NoNeedLoginAttribute : Attribute
    {
        public static bool IsIgnore(ActionExecutingContext filterContext)
        {
            if (filterContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes(typeof(NoNeedLoginAttribute), true).Count() > 0 ||
               filterContext.ActionDescriptor.GetCustomAttributes(typeof(NoNeedLoginAttribute), true).Count() > 0)
            {
                return true;
            }
            return false;
        }
    }
}